package com.cj.startup.event

import com.cj.startup.Startup
import java.util.concurrent.ConcurrentHashMap

object StartupObservable {
    private val mObserveMap: ConcurrentHashMap<StartupObserve, List<Class<out Startup<*>>>?> =
        ConcurrentHashMap<StartupObserve, List<Class<out Startup<*>>>?>()

    fun addObserver(observe: StartupObserve, observerObject: List<Class<out Startup<*>>>?) {
        mObserveMap.put(observe, observerObject ?: emptyList())
    }

    fun removeObserver(observe: StartupObserve) {
        val remove = mObserveMap.remove(observe)
        observe.call(StartupObserve.Event.DISPOSE, null, null)
    }

    fun removeObserver(clazz: Class<out Startup<*>>) {
        val iterator = mObserveMap.entries.iterator()
        while (iterator.hasNext()) {
            val entry = iterator.next()
            val v = entry.value
            if (v?.contains(clazz) == true) {
                iterator.remove()
                entry.key.call(StartupObserve.Event.DISPOSE, null, null)
            }
        }
    }

    fun notifyObserver(event: StartupObserve.Event, clazz: Class<out Startup<*>>, result: Any?) {
        val iterator = mObserveMap.iterator()
        while (iterator.hasNext()) {
            val entry = iterator.next()
            val v = entry.value
            if (v == null || v.isEmpty() || v.contains(clazz)) {
                entry.key.call(event, clazz, result)
            }
        }
    }

}